package com.example.demo.config.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author: wuhong-016
 * @time: 2021/3/5 10:19
 * @version: v1.0.0
 * @description:动态数据源配置
 */
@Aspect
@Component
@Order(-1)
public class DataSourceAspect {

    private Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Around("execution(* com.example.demo.service.impl.*.*(..))")
    @Order(1)
    public Object handleDataSource(ProceedingJoinPoint joinPoint) throws Throwable {

        //同时支持类和方法上的注解，以方法上为主
        TargetDataSource classDataSource = joinPoint.getTarget().getClass().getAnnotation(TargetDataSource.class);
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        TargetDataSource methodDataSource = methodSignature.getMethod().getDeclaredAnnotation(TargetDataSource.class);

        String name;

        if (methodDataSource != null) {
            name = methodDataSource.name();
        } else if (classDataSource != null) {
            name = classDataSource.name();
        } else {
            name = DataSourceConfig.DEFAULT;
        }

        DynamicDataSourceHolder.set(name);

        return joinPoint.proceed();
    }

}
